import json
import os
from swaggerParser import SwaggerParser
from openpyxl import Workbook

def generate_test_cases(swagger_path, output_format='json'):
    """
    根据Swagger文档生成测试用例
    :param swagger_path: Swagger文档的路径
    :param output_format: 输出格式，支持'json'和'excel'
    :return: 无
    """
    # 解析Swagger文档
    swagger_data = SwaggerParser.parse_from_file(swagger_path)
    paths = swaggerParser.get_paths(swagger_data)

    # 初始化测试用例列表
    test_cases = []

    # 遍历所有路径和HTTP方法
    for path, methods in paths.items():
        for method, operation in methods.items():
            # 获取请求参数和响应信息
            parameters = SwaggerParser.get_operation_parameters(operation)
            responses = SwaggerParser.get_operation_responses(operation)

            # 构建测试用例
            test_case = {
                'path': path,
                'method': method,
                'parameters': [param['name'] for param in parameters],
                'expected_status_code': responses[0]['code'],
                'expected_response': responses[0]['description']
            }

            # 添加到测试用例列表
            test_cases.append(test_case)

    # 根据输出格式生成文件
    if output_format == 'json':
        with open('test_cases.json', 'w') as f:
            json.dump(test_cases, f, indent=4)
    elif output_format == 'excel':
        # 创建Excel工作簿和工作表
        wb = Workbook()
        ws = wb.active

        # 写入表头
        ws.append(['Path', 'Method', 'Parameters', 'Expected Status Code', 'Expected Response'])

        # 写入测试用例数据
        for test_case in test_cases:
            ws.append([test_case['path'], test_case['method'], ', '.join(test_case['parameters']),
                       test_case['expected_status_code'], test_case['expected_response']])

        # 保存Excel文件
        wb.save('test_cases.xlsx')

# 使用示例
swagger_path = 'path/to/your/swagger.json'  # 替换为你的Swagger文档路径
generate_test_cases(swagger_path, output_format='excel')  # 生成Excel格式的测试用例